package com.yingda.activity;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.yingda.ad.Constants;
import com.yingda.ad.R;
import com.yingda.bean.Student;
import com.yingda.bean.WorkBean;
import com.yingda.eventbus.EventBus;
import com.yingda.eventbus.Subscriber;
import com.yingda.eventbus.ThreadMode;
import com.yingda.fragment.ReadTabFragment;
import com.yingda.fragment.ReadTabTwoFragment;
import com.yingda.utils.ExcelUtils;
import com.yingda.utils.ExecutorsUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ExcelActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_create_excel;
    private TextView tv_read_excel2;
    public static final String TAG = "ExcelActivity";

    private TextView tv_read_excel1;
    private Map<String, WorkBean> workBeanMap2;
    private Map<String, WorkBean> workBeanMap1;
    private TextView tv_open_file;
    private ActivityResultLauncher<Intent> filePickerLauncher;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.excel_layout);

        tv_create_excel = findViewById(R.id.tv_create_excel);
        tv_read_excel2 = findViewById(R.id.tv_read_excel2);
        tv_read_excel1 = findViewById(R.id.tv_read_excel1);
        tv_open_file = findViewById(R.id.tv_open_file);


        tv_create_excel.setOnClickListener(this);

        tv_read_excel2.setOnClickListener(this);
        tv_read_excel1.setOnClickListener(this);
        tv_open_file.setOnClickListener(this);

        //   initPre();
        EventBus.getDefault().register(this);

        // 初始化文件选择器
        filePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        Uri selectedFileUri = result.getData().getData();
                        handleSelectedFile(selectedFileUri);
                    }
                }
        );
    }

    private List<Student> students = new ArrayList<>();

    private void createExtel() {
//        Student student = new Student();
//        student.setAge(18);
//        student.setGender("女");
//        student.setName("小红");
//        student.setId(001);
//        students.add(student);
//
//        Student student2 = new Student();
//        student2.setAge(16);
//        student2.setGender("男");
//        student2.setName("小明");
//        student2.setId(002);
//        students.add(student2);
        ExecutorsUtils.getInstance().getSingleThread(new Runnable() {
            @Override
            public void run() {
                List<WorkBean> workBeans = isMapContainedInAnother(workBeanMap1, workBeanMap2);
                ExcelUtils.getInstance().createExcel(workBeans, ExcelActivity.this);
            }
        });
    }


    public List<WorkBean> isMapContainedInAnother(Map<String, WorkBean> mapA, Map<String, WorkBean> mapB) {
        List<WorkBean> workBeans = new ArrayList<>();
        for (Map.Entry<String, WorkBean> entry : mapA.entrySet()) {
            String key = entry.getKey();
            com.yingda.bean.WorkBean value = entry.getValue();

            // 检查 mapB 是否包含 mapA 的键值对
            if (mapB.containsKey(key)) {
                workBeans.add(value);
            }
        }
        return workBeans;  // 所有键值对都在 mapB 中
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_create_excel:
                showWaitingDlg();
                ExecutorsUtils.getInstance().getSingleThread(() -> createExtel());
                break;
            case R.id.tv_open_file:
                //打开本地文件
                openDownloadFolder();
                break;
            case R.id.tv_read_excel1:
                showWaitingDlg();
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fl_content, new ReadTabFragment())
                        .commitAllowingStateLoss();

                //先把客户的表格导入到手机
                //adb push /Users/duanlexian/Desktop/十位员工 号的的的文件夹.xls  /storage/emulated/0/Download
                //adb push /Users/duanlexian/Desktop/延长工期 队2024-08-03任工作务信息表.xls /storage/emulated/0/Download
//                File fileDir = Environment.getExternalStorageDirectory();
//                String path = fileDir.getAbsoluteFile() + File.separator + "Download";
//                File xlsFile = new File(path, "延长工期 队2024-08-03任工作务信息表.xls");
                //  readExcel(xlsFile);
                break;
            case R.id.tv_read_excel2:

                showWaitingDlg();

                //先把客户的表格导入到手机
                //adb push /Users/duanlexian/Desktop/十位员工 号的的的文件夹.xls  /storage/emulated/0/Download
                //adb push /Users/duanlexian/Desktop/延长工期 队2024-08-03任工作务信息表.xls /storage/emulated/0/Download
                File fileDir = Environment.getExternalStorageDirectory();
                String path = fileDir.getAbsoluteFile() + File.separator + "Download";
                File xlsFile = new File(path, "延长工期 队2024-08-03任工作务信息表.xls");
                //  readExcel(xlsFile);

                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fl_content, new ReadTabTwoFragment())
                        .commitAllowingStateLoss();

                break;
        }
    }

    private void openDownloadFolder() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.setType("*/*");  // 显示所有文件类型
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        // 设置初始路径为 Download 目录
        Uri downloadUri = Uri.parse(DocumentsContract.buildRootUri("com.android.externalstorage.documents", "primary:Download").toString());
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, downloadUri);

        filePickerLauncher.launch(intent);
    }

    private void handleSelectedFile(Uri fileUri) {
        if (fileUri != null) {
            Toast.makeText(this, "选中文件的 URI: " + fileUri.toString(), Toast.LENGTH_LONG).show();
            readFileContent(fileUri);
        } else {
            Toast.makeText(this, "未选中文件", Toast.LENGTH_SHORT).show();
        }
    }

    private void readFileContent(Uri fileUri) {
        ContentResolver contentResolver = getContentResolver();
        try (InputStream inputStream = contentResolver.openInputStream(fileUri);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {

            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }

            // 显示读取的内容
            String fileContent = stringBuilder.toString();
            Toast.makeText(this, "文件内容:\n" + fileContent, Toast.LENGTH_LONG).show();

        } catch (IOException e) {
            Toast.makeText(this, "读取文件失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Subscriber(tag = Constants.DIALOGCLOSE, mode = ThreadMode.MAIN)
    public void setGuestFreeMode(String count) {
        dismissWaitingDlg();
    }

    //表格 2 中的数据
    @Subscriber(tag = Constants.READTWO, mode = ThreadMode.MAIN)
    public void readxls2(Map<String, WorkBean> workBeanMap2) {
        this.workBeanMap2 = workBeanMap2;
        // 使用 for-each 循环遍历 entrySet
        for (Map.Entry<String, WorkBean> entry : workBeanMap2.entrySet()) {
            String key = entry.getKey();
            WorkBean value = entry.getValue();
            Log.i(TAG, "readxls2: key=" + key + "name=" + value.getName());
        }
    }

    @Subscriber(tag = Constants.READONE, mode = ThreadMode.MAIN)
    public void readxls1(Map<String, WorkBean> workBeanMap1) {
        this.workBeanMap1 = workBeanMap1;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ExecutorsUtils.getInstance().closeThread();
        EventBus.getDefault().unregister(this);
        dismissWaitingDlg();

    }
}
